home *** CD-ROM | disk | FTP | other *** search
/ L' Effet Pommier 3 / L'Effet Pommier - Volume 03.iso / Programmation / gray image 2.1 / write_pgm.cc < prev    next >
Text File  |  1995-05-03  |  2KB  |  63 lines

  1. // This may look like C code, but it is really -*- C++ -*-
  2. /*
  3.  ************************************************************************
  4.  *
  5.  *               Grayscale Image
  6.  *
  7.  *    Write the image into the file in the  Portable GrayMap (pgm) format
  8.  * 
  9.  * The program writes a "binary" (RAWBITS) pgm file of the following format
  10.  *   - A "magic number" for identifying the file type.  A pgm
  11.  *     file's RAWBITS magic number is two characters "P5".
  12.  *   - Whitespace (blanks, TABs, CRs, LFs).
  13.  *   - A width, formatted as ASCII characters in decimal.
  14.  *   - Whitespace.
  15.  *   - A height, again in ASCII decimal.
  16.  *   - Whitespace.
  17.  *   - The maximum gray value, again in ASCII decimal. For RAWBITS pgm file
  18.  *       the maximum grayscale value cannot exceed 255.
  19.  *   - A _single_ character of whitespace (typically a newline).
  20.  *   - Width * height gray values, each as plain bytes, between
  21.  *     0 and the specified maximum value, stored consecutivly, 
  22.  *     starting at the top-left corner of the graymap, proceding in normal
  23.  *     English reading order. 
  24.  *     A value of 0 means black, and the maximum value means white.
  25.  *
  26.  * For more detail, see documentation on PBMPLUS package (specifically,
  27.  * pgm(5)).
  28.  *
  29.  * $Id: write_pgm.cc,v 2.0 1995/03/06 20:58:24 oleg Exp oleg $
  30.  *
  31.  ************************************************************************
  32.  */
  33.  
  34. #include "image.h"
  35. #include "endian_io.h"
  36.  
  37. void IMAGE::write_pgm(const char * file_name,const char * title) const
  38. {
  39.   is_valid();
  40.  
  41.   message("\nPreparing a PGM file with name '%s'\n",file_name);
  42.  
  43.   assure(bits_per_pixel <= 8,
  44.      "Sorry, the program cannot write images with depth > 8");
  45.  
  46.   const card max_gray_value = (1<<bits_per_pixel)-1;
  47.  
  48.   EndianOut outf(file_name);
  49.   assert( outf.good() );
  50.  
  51.                 // Write the header
  52.   outf << "P5\n" << ncols << ' ' << nrows << '\n' << max_gray_value << '\n';
  53.  
  54.   class WritePixelMatrix : public PixelPrimAction
  55.   {
  56.     EndianOut& outf;
  57.     void operation(GRAY& pixel)    { outf.write_byte(pixel); }
  58.     public: WritePixelMatrix(EndianOut& ostream) : outf(ostream) {}
  59.   };
  60.   (*(IMAGE*)this).apply(WritePixelMatrix(outf));
  61.   outf.close();
  62. }
  63.